//
//  YNSessionOpenfireManager.m
//  Messenger
//
//  Created by yineng on 2019/8/20.
//  Copyright © 2019 YN-APP-iOS. All rights reserved.
//

#import "YNSessionOpenfireManager.h"
#import "YNSessionMessageManager.h"
#import "YNIMFrameworkMacro.h"
#import "YNXMPPprotocol.h"
#import "YNXMPPManager.h"
#import "YNIMTool.h"

#define openfireResource @"meeting"

@interface YNSessionOpenfireManager()<YNXMPPprotocol,UIAlertViewDelegate>
{
    YNSessionMessageManager *receiveMessage;
    YNXMPPManager*xmppManager;
}
/////业务相关加入的属性
//进入房间时房间内已有人员id集合
@property(nonatomic,strong)NSMutableArray<NSString*>*inRoomUserIds;

@end

@implementation YNSessionOpenfireManager

#pragma mark 初始化

+(instancetype)shareSessionOpenfireManager{
    static YNSessionOpenfireManager*manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[YNSessionOpenfireManager alloc]init];
    });
    return manager;
}

-(void)initXMPPWithServer:(NSString*)server companyCode:(NSString*)code imId:(NSString*)imId userName:(NSString*)userName{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleStandardBindingError_409) name:@"handleStandardBindingError_409" object:nil];
    xmppManager = [[YNXMPPManager alloc]initXMPPWithServer:server companyCode:code imId:imId loginName:userName delegate:self minimalist:YES];
    
    NSString*error = [xmppManager connectWithDomain:openfireDomainName resource:openfireResource];
    if (error != nil) {
        if (self.joinRoomFailBlock) {
            self.joinRoomFailBlock(@"用户错误");
        }
    }
}

#pragma mark __配置消息接收和发送
-(void)setMessageSendAndGet{
    receiveMessage = [[YNSessionMessageManager alloc] init];
    receiveMessage.roomId=self.roomId;
    [receiveMessage addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [receiveMessage activate:[xmppManager getXMPPStream]];
    WEAKSELF
    receiveMessage.joinRoomSuccessBlock = ^{
        weakSelf.joinRoomSuccessBlock(weakSelf.inRoomUserIds);
        [weakSelf.inRoomUserIds removeAllObjects];
    };
    receiveMessage.joinRoomFailBlock = ^(NSString * _Nonnull errorMessage) {
        weakSelf.joinRoomFailBlock(errorMessage);
    };
    receiveMessage.inRoomUserBlock = ^(NSString * _Nonnull userId) {
        [weakSelf.inRoomUserIds addObject:userId];
    };
}

#pragma mark - YNXMPPprotocol
-(void)xmppStreamDidConnect{
    [xmppManager xmppAuthenticatePassword:_sessionIMPassword];
}
-(void)didError:(NSString *)errorMsg{
    if (self.joinRoomFailBlock) {
        self.joinRoomFailBlock(errorMsg);
    }
}
-(void)xmppStreamDidAuthenticate{
    debugLog(@"云端openfire登录成功！！！开始执行加入房间")
    //去加入房间
    [self sendPresenceJoinTRTCRoom:self.roomId];
}
-(void)didNotAuthenticate{
    if (self.needRegisterBlock) {
        self.needRegisterBlock();
    }
    self.registerSuccessBlock = nil;
    __block YNXMPPManager* BxmppManager = xmppManager;
    self.registerSuccessBlock = ^{
        debugLog(@"云端openfire注册成功再去认证");
        [BxmppManager xmppAuthenticatePassword:_sessionIMPassword];
    };
}
-(void)xmppStreamConnectDidTimeout{
    [[NSNotificationCenter defaultCenter] postNotificationName:YNNotificationCloudOpenfirOnline object:[NSNumber numberWithBool:NO]];
   if (self.joinRoomFailBlock) {
       self.joinRoomFailBlock(@"连接超时");
   }
}
-(void)sameTimeLogin{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"下线通知"
                                                            message:@"您已在其他终端进入会议"
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定", nil];
        alertView.tag=1002;
        [alertView show];
    });
}
-(void)xmppStreamDidDisconnect:(NSInteger)code{
    [[NSNotificationCenter defaultCenter] postNotificationName:YNNotificationCloudOpenfirOnline object:[NSNumber numberWithBool:NO]];
    if (self.joinRoomFailBlock) {
        self.joinRoomFailBlock(@"连接失败");
    }
}
#pragma mark YNXMPPprotocol end

-(void)handleStandardBindingError_409{
    [self removeDelegate];
    [self teardownStream];
    if (self.joinRoomFailBlock) {
        self.joinRoomFailBlock(@"您已经在手机端/电脑端进入视频会议！");
    }
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag==1002) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter]postNotificationName:@"nibeijidiaoxianle" object:nil];
        });
    }
}
#pragma mark __业务逻辑调用的方法
-(void)sendMessageWith:(NSString*)body toUserId:(NSString*)toUserId message:(YNMessage*)message netConnect:(BOOL)netConnect{
    [receiveMessage sendMessageWith:body toUserId:toUserId message:message netConnect:netConnect];
}
-(void)sendMessageChangeSubjectSpeakIds:(NSArray<NSDictionary*>*)speaks{
    [receiveMessage sendMessageChangeSubjectSpeakIds:speaks];
}
//加入/创建房间
-(void)sendPresenceJoinTRTCRoom:(NSString*)roomId{
    if ([YNIMTool isEmptyString:roomId]) {
        return;
    }
    [receiveMessage sendPresenceJoinTRTCRoom:roomId];
}

- (void)teardownStream
{
    [xmppManager logout];
    debugLog(@"云端openfire连接、资源等销毁了");
}

- (void)removeDelegate
{
    [receiveMessage removeDelegate:self delegateQueue:dispatch_get_main_queue()];
    [receiveMessage deactivate];
    receiveMessage=nil;
    
    self.registerSuccessBlock=nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"handleStandardBindingError_409" object:nil];
}
#pragma mark __getter
-(NSMutableArray<NSString *> *)inRoomUserIds{
    if (!_inRoomUserIds) {
        _inRoomUserIds=[NSMutableArray array];
    }
    return _inRoomUserIds;
}

-(void)dealloc{
    //移除消息接收代理
    [self removeDelegate];
    //清除流配置
    [self teardownStream];
}

@end
